#include <QtGui/QHBoxLayout>

#include <osgQt/GraphicsWindowQt>
#include <osg/GraphicsContext>
#include <osgGA/TrackballManipulator>
#include <osgViewer/ViewerEventHandlers>
#include <osgDB/ReadFile>
#include "viewerwidget.h"

ViewerWidget::ViewerWidget(QWidget *parent)
	: QWidget(parent)
{
	initCameraConfig();
	setSceneData(osgDB::readNodeFile("axes.osgt"));
	connect(&timer,SIGNAL(timeout()),this,SLOT(update()));
	timer.start(10);
}

void ViewerWidget::initCameraConfig()
{
	osg::ref_ptr<osg::DisplaySettings> ds = osg::DisplaySettings::instance().get();
	osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
	traits->x = 0;
	traits->y = 0;
	traits->width = this->width();
	traits->height = this->height();
	traits->windowDecoration = false;
	traits->windowName = "";
	traits->doubleBuffer = true;
	traits->alpha = ds->getMinimumNumAlphaBits();
	traits->stencil = ds->getMinimumNumStencilBits();
	traits->sampleBuffers = ds->getMultiSamples();
	traits->samples = ds->getNumMultiSamples();

	osg::ref_ptr<osg::Camera> camera = new osg::Camera;
	camera->setGraphicsContext(new osgQt::GraphicsWindowQt(traits));
	camera->setClearColor(osg::Vec4(0.2,0.2,0.6,1.0));
	camera->setViewport(0,0,traits->width,traits->height);
	camera->setProjectionMatrixAsPerspective(
		30.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 1.0f, 10000.0f );

	setCamera(camera.get());
	setCameraManipulator(new osgGA::TrackballManipulator);
	addEventHandler(new osgViewer::StatsHandler);


	osgQt::GraphicsWindowQt* gwq = dynamic_cast<osgQt::GraphicsWindowQt*>(camera->getGraphicsContext());
	QWidget* widget = gwq?gwq->getGLWidget() : NULL;

	QHBoxLayout* layout = new QHBoxLayout;
	layout->addWidget(widget);
	setLayout(layout);
}

void ViewerWidget::paintEvent(QPaintEvent *)
{
	frame();
}
ViewerWidget::~ViewerWidget()
{

}
